package controller;

import com.alibaba.excel.EasyExcel;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class BaseController {

    public <T> List<T> readExcel(MultipartFile file, Class<T> cls) {
        List<T> objects = new ArrayList<>();
        try {
          objects =  EasyExcel.read(file.getInputStream(), cls, null).sheet().doReadSync();
        } catch (IOException e) {
            System.out.println("读取失败");
        }
        return objects;
    }

    public <T> void exportExcel(HttpServletResponse response, Class<T> cls, List<T> list, String fileName) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8)
                    .replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), cls).sheet().doWrite(list);

        } catch (Exception e) {
            System.out.println("导出失败");
        }

    }





}
